package jdk6.jtable;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.RowFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;

/**
 * Description: jdk1.6新特性：JTable的排序和过滤（JTable新功能)
 * 原来的JTable基本上是只能显示数据，在JDK6新增了对JTable的排序和过滤功能，下面代码演示了这两个功能 
 * 
 * 个人认为：在开发swt的时候可能会非常有用吧
 * @author Kwum
 * @date 2017年6月26日 下午3:11:19
 * @version 1.0
 */

public class Run {
    
    private static String data[][] = {
            {"China","Beijing","Chinese"},
            {"America","Washington","English"},
            {"Korea","Seoul","Korean"},
            {"Japan","Tokyo","Japanese"},
            {"France","Paris","French"},
            {"England","London","English"},
            {"Germany","Berlin","German"},
    };
    
    private static String titles[] = {"Country","Capital","Language"};

    public static void main(String[] args) {
        DefaultTableModel m = new DefaultTableModel(data,titles);
        JTable t = new JTable(m);
        final TableRowSorter<DefaultTableModel> sorter = new TableRowSorter<DefaultTableModel>(m);
        t.setRowSorter(sorter); //为JTable设置排序器

        JScrollPane sPane = new JScrollPane();
        sPane.setViewportView(t);

        JPanel p = new JPanel();
        p.setLayout(new BoxLayout(p,BoxLayout.X_AXIS));
        JLabel l = new JLabel("Criteria:");
        final JTextField tf = new JTextField();
        JButton b = new JButton("Do Filter");
        p.add(l);
        p.add(tf);
        p.add(b);
        b.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if(tf.getText().length()==0){
                    sorter.setRowFilter(null);
                }else{
                    //为JTable设置基于正则表达式的过滤条件
                    sorter.setRowFilter(RowFilter.regexFilter(tf.getText()));
                }
            }
        });
  
        JFrame f = new JFrame("JTable Sorting and Filtering");
        f.getContentPane().add(sPane,BorderLayout.CENTER);
        f.getContentPane().add(p,BorderLayout.SOUTH);
        f.setSize(400,300);
        f.setVisible(true);
    }

}
